package com.nl.lib_project.net

import android.annotation.SuppressLint
import com.hjq.http.EasyConfig
import com.hjq.http.config.IRequestInterceptor
import com.hjq.http.config.IRequestServer
import com.hjq.http.model.HttpHeaders
import com.hjq.http.model.HttpParams
import com.hjq.http.request.HttpRequest
import com.nl.lib_core.BaseApplication
import com.nl.lib_core.tool.SPUtils
import com.nl.lib_project.datas.LocalDbAutism
import com.nl.lib_project.net.server.EasyHttpServer
import com.nl.lib_project.net.server.PrivateServer
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response

/** 作者: wangfei 创建时间: 2021/10/12 包名: com.nl.lib_project.proxy 类名: EasyNetProxy */
open class EasyNetProxy {

  companion object {
    private var okHttpClient = createOkhttpClient()

    /**
     * 新建okhttpClient
     * @param ip 代理服务器地址
     * @param port 代理服务器端口号
     */
    fun createOkhttpClient(ip: String? = null, port: Int? = null): OkHttpClient {
      val client =
          OkHttpClient.Builder()
              .connectTimeout(LocalDbAutism.HTTP_CALL_TIME_OUT_TIME, TimeUnit.MILLISECONDS)
              .callTimeout(LocalDbAutism.HTTP_CALL_TIME_OUT_TIME, TimeUnit.MILLISECONDS)
      if (ip != null && port != null) {
        if (port <= LocalDbAutism.PORT_MAX) {
          // 设置代理服务器地址
          client.proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress(ip, port)))
        }
      }
      val build = client.build()
      // 单个Host最大请求连接数
      build.dispatcher().maxRequestsPerHost = 64
      return build
    }
    @SuppressLint("SimpleDateFormat")
    fun getInit() {
      // 网络请求框架初始化
      var server: IRequestServer = EasyHttpServer()
      // 如果当前有私有服务器的话则走私有服务器
      BaseApplication.instance?.let {
        val spHost = SPUtils[it, LocalDbAutism.SP_PRIVATE_HOST, ""] as String?
        if (spHost.isNullOrBlank().not()) {
          server = PrivateServer(it)
        }
        // 检查是否配置过代理服务器
        val proxyHost = SPUtils[it, LocalDbAutism.SP_PROXY_HOST, ""] as String
        val proxyPort = SPUtils[it, LocalDbAutism.SP_PROXY_PORT, ""] as String
        if (proxyHost.isNotEmpty() && proxyPort.isNotEmpty()) {
          okHttpClient = createOkhttpClient(proxyHost, proxyPort.toInt())
        }
      }

      EasyConfig.with(okHttpClient)
          // 是否打印日志
          .setLogEnabled(true)
          // 设置服务器配置
          .setServer(server) // 设置请求处理策略
          .setHandler(BaseApplication.instance?.let { RequestHandler(it) })
          .setInterceptor(
              object : IRequestInterceptor {
                override fun interceptArguments(
                    httpRequest: HttpRequest<*>?,
                    params: HttpParams?,
                    headers: HttpHeaders?
                ) {
                  BaseApplication.instance?.let {
                    val token = SPUtils[it, LocalDbAutism.SP_KEY_TOKEN, ""] as String?
                    if (!token.isNullOrEmpty()) {
                      headers?.put("Access-Token", token)
                    }
                  }
                  super.interceptArguments(httpRequest, params, headers)
                }

                override fun interceptRequest(
                    httpRequest: HttpRequest<*>?,
                    request: Request?
                ): Request {
                  return super.interceptRequest(httpRequest, request)
                }

                override fun interceptResponse(
                    httpRequest: HttpRequest<*>?,
                    response: Response?
                ): Response {
                  return super.interceptResponse(httpRequest, response)
                }
              })
          // 设置请求参数拦截器
          .setRetryCount(LocalDbAutism.HTTP_RETRY_COUNT) // 设置请求重试时间
          .setRetryTime(LocalDbAutism.HTTP_RETRY_TIME) // 添加全局请求参数
          .into()
    }
  }
}
